package com.hmall.common.userinterface;

import cn.hutool.core.util.StrUtil;
import com.hmall.common.utils.UserContext;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserinfoInterfact implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取头信息的userid
        String userid = request.getHeader("userinfo");
        if (StrUtil.isNotBlank(userid)) {
            // 将用户id存如 ThreadLoacal中
            UserContext.setUser(Long.parseLong(userid));
        }
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完成后要清楚ThreadLocal 的信息
        UserContext.removeUser();
    }




}
